#pragma once

#include "comm.hpp"
#include "Log.hpp"
#include "inetAddr.hpp"
#include "Thread.hpp"
#include "ThreadPool.hpp"
#include "Dict.hpp"
#include <functional>
#include <thread>

using namespace LogModule;
using namespace ThreadPoolModule;

using task_t = std::function<void()>;
using func_t = std::function<std::string(const std::string &word, InetAddr &addr)>;

const static int defaultfd = -1;
const static int backlog = 8;

class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t port, func_t func)
        :_port(port),
        _listensockfd(defaultfd),
         _isrunning(false),
         _func(func)   
    {}

    void Init()
    {
        // signal(SIGCHLD, SIG_IGN); // 推荐做法
        // 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success: " << _listensockfd;

        // bind信息
        InetAddr addr(_port);
        int n = bind(_listensockfd, addr.NetAddrPtr(), addr.NetAddrLen());
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success: " << _listensockfd;

        // 设置socket状态为listen
        n = listen(_listensockfd, backlog);
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success: " << _listensockfd;
    }
    
    class ThreadData
    {
    public:
        ThreadData(int fd, InetAddr ar, TcpServer *ptr)
            :sockfd(fd), addr(ar), tsvr(ptr)
        {}
        int sockfd;
        InetAddr addr;
        TcpServer *tsvr;
    };

    // 短服务: 线程池
    // 长服务: 多线程多进程比较合适
    void Server(int sockfd, InetAddr &peer)
    {
        while(1)
        {
            char buff[1024];
            // 读取数据
            ssize_t n = read(sockfd, buff, sizeof(buff) - 1);
            std::string echo;
            if(n > 0)
            {
                buff[n] = 0;
                LOG(LogLevel::INFO) << peer.StringAddr() << " say: " << buff;
                echo = _func(buff, peer);
            }
            else if(n == 0)
            {
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " exit";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " error";
                close(sockfd);
                break;
            }
            // 写回数据
            // std::string echo = "echo# ";
            // echo += buff;
            write(sockfd, echo.c_str(), echo.size());
        }
    }

    static void *Routine(void *args)
    {
        pthread_detach(pthread_self()); // 分离, 不用join
        ThreadData *td = (ThreadData*)args;
        td->tsvr->Server(td->sockfd, td->addr);
        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while(_isrunning)
        {
            // 获取链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, CONV(peer), &len);
            if(sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }

            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept success: " << addr.StringAddr(); 

            // testV -- 单进程程序 -- 不会存在
            Server(sockfd, addr);

            // v1 -- 多进程版本 --
            // pid_t id = fork();
            // if(id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "fork error";
            //     exit(FORK_ERR);
            // }
            // else if(id == 0)
            // {
            //     // 子进程
            //     // 不让子进程访问listensocket
            //     close(_listensockfd);
            //     if(fork() > 0) // 再次fork, 子进程退出
            //         exit(OK);

            //     Server(sockfd, addr); // 孙子进程
            //     exit(OK);
            // }
            // else
            // {
            //     //父进程
            //     close(sockfd);
            //     pid_t rid = waitpid(id, nullptr, 0);
            //     (void)rid;
            // }

            // v2 -- 多线程版本 --
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, addr, this);
            // pthread_create(&tid, nullptr, Routine, (void*)td);

            // v3 -- 线程池版本 --
            // ThreadPool<task_t>::GetInstance()->Equeue([this, &sockfd, &addr](){
            //     this->Server(sockfd, addr);
            // });
        }
        _isrunning = false;
    }

    ~TcpServer(){}
private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
    func_t _func;
};